<?php


namespace App\Remote\Orm;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class BaseOrmRemote
{

    /**
     * @param $path
     * @return string
     */
    public final static function getRequestUrl($path): string
    {
        return vsprintf("%s%s", [
            config('orm.domain'),
            $path
        ]);
    }

    /**
     * @param string $method
     * @param string $url
     * @param array|null $body
     * @param array|null $headers
     * @param string $bodyType
     * @return array|null|false
     * @throws GuzzleException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function request(
        string $method,
        string $url,
        array $body = null,
        array  $headers = null,
        string $bodyType = 'body'
    ){
        $client   = new GuzzleClient(['http_errors' => false]);
        $response = $client->request($method, self::getRequestUrl($url), [
            $bodyType => $body ?: [],
            'headers' => array_merge([
                'internal-key'     => config('orm.internalKey'),
                'internal-token'   => config('orm.internalValue'),
                'X-Requested-With' => 'XMLHttpRequest',
                'Accept'           => 'application/json',
            ], $headers ?: []),
            'timeout' => 10
        ]);
        $contents = $response->getBody()->getContents();
        return json_decode($contents, true);
    }

}
